package com.sanyuan.cloud.framework.common.util.encrypt;

import javax.crypto.Cipher;
import javax.crypto.KeyGenerator;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Base64;

/**
 * @Description: AES对称加密Utils
 * @Author: wuyuwei
 * @Date: 2025/3/20
 */
public class AESUtils {

    /**
     * 生成密钥
     * @param keySize
     * @return
     * @throws NoSuchAlgorithmException
     */
    public static SecretKey generateAESKey(int keySize) throws NoSuchAlgorithmException {
        KeyGenerator keyGenerator = KeyGenerator.getInstance("AES");
        keyGenerator.init(keySize); // 密钥长度：128, 192, 256 位
        return keyGenerator.generateKey();
    }

    /**
     * 加密
     * @param plaintext 明文
     * @param secretKey 密钥
     * @return
     * @throws Exception
     */
    public static String encrypt(String plaintext, SecretKey secretKey) throws Exception {
        // 初始化加密器
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        byte[] ivBytes = new byte[16]; // IV 长度需与块大小一致（AES 块大小为 128 位）
        SecureRandom random = new SecureRandom();
        random.nextBytes(ivBytes);
        IvParameterSpec iv = new IvParameterSpec(ivBytes);
        cipher.init(Cipher.ENCRYPT_MODE, secretKey, iv);

        // 加密数据
        byte[] encryptedBytes = cipher.doFinal(plaintext.getBytes("UTF-8"));

        // 合并 IV 和密文（IV 不需要保密，但需在解密时使用）
        byte[] combined = new byte[ivBytes.length + encryptedBytes.length];
        System.arraycopy(ivBytes, 0, combined, 0, ivBytes.length);
        System.arraycopy(encryptedBytes, 0, combined, ivBytes.length, encryptedBytes.length);

        return Base64.getEncoder().encodeToString(combined);
    }

    /**
     * 解密
     * @param encryptedText 密文
     * @param secretKey 密钥
     * @return
     * @throws Exception
     */
    public static String decrypt(String encryptedText, SecretKey secretKey) throws Exception {
        byte[] combined = Base64.getDecoder().decode(encryptedText);

        // 分离 IV 和密文
        byte[] ivBytes = new byte[16];
        byte[] encryptedBytes = new byte[combined.length - ivBytes.length];
        System.arraycopy(combined, 0, ivBytes, 0, ivBytes.length);
        System.arraycopy(combined, ivBytes.length, encryptedBytes, 0, encryptedBytes.length);

        // 初始化解密器
        Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");
        IvParameterSpec iv = new IvParameterSpec(ivBytes);
        cipher.init(Cipher.DECRYPT_MODE, secretKey, iv);

        // 解密数据
        byte[] decryptedBytes = cipher.doFinal(encryptedBytes);
        return new String(decryptedBytes, "UTF-8");
    }

    public static void main(String[] args) throws Exception {
        // 生成密钥
        SecretKey secretKey = generateAESKey(256);
//        String encodedKey = Base64.getEncoder().encodeToString(secretKey.getEncoded());
        String encodedKey = "yQOZFsw0g/R6q9ILARjXVPu0Rt1vYQJObLI7yCJ4s4U=";// 后续用的密钥
        System.out.println("AES Key: " + encodedKey);

        // 加密示例
        String plaintext = "123456";
        String encryptedText = encrypt(plaintext, secretKey);
        System.out.println("Encrypted Text: " + encryptedText);

        // 解密示例
        String decryptedText = decrypt(encryptedText, secretKey);
        System.out.println("Decrypted Text: " + decryptedText);
    }

}
